import queue
import pyaudio
from voice.recorder.recorder import Recorder
from common.log import logger

FORMAT = pyaudio.paInt16
CHANNELS = 1
SAMPLE_RATE = 16000
CHUNK_SIZE = 512


class PyAudioRecorder(Recorder):

    def __init__(self, input_queue: queue.Queue):
        super().__init__(input_queue)
        self._p = pyaudio.PyAudio()
        self.stream = None
        self.running = False

    def start_recording(self):
        if self.running:
            raise RuntimeError("Recorder already running")
        self.stream = self._p.open(
            format=FORMAT,
            channels=CHANNELS,
            rate=SAMPLE_RATE,
            input=True,
            frames_per_buffer=CHUNK_SIZE,
        )
        self.running = True
        self.thread.start()

    def stop_recording(self):
        if not self.running:
            return
        self.running = False
        if self.stream:
            self.stream.stop_stream()
            self.stream.close()
        if self._p:
            self._p.terminate()
        if self.thread:
            self.thread.join()

    def _read(self):
        """读取音频数据块"""
        while self.running:
            try:
                audio_chunk = self.stream.read(CHUNK_SIZE)
                self.input_queue.put(audio_chunk)
            except Exception as e:
                logger.error(f"Recorder error: {e}")
            finally:
                self.stop_recording()
